package com.crm.smartmachine.ui.test

import android.os.Bundle
import android.text.TextUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.cheng.library.common.clickNoRepeat
import com.cheng.library.common.toast
import com.crm.smartmachine.R
import com.crm.smartmachine.base.SmartBaseFragment
import com.crm.smartmachine.databinding.FragmentModbusSlaveBinding
import com.zgkxzx.modbus4And.requset.ModbusParam
import com.zgkxzx.modbus4And.requset.ModbusReq
import com.zgkxzx.modbus4And.requset.OnRequestBack
import net.wimpi.modbus.ModbusCoupler
import net.wimpi.modbus.net.ModbusTCPListener
import net.wimpi.modbus.procimg.*
import java.net.InetAddress

class ModbusSlaveFragment : SmartBaseFragment<FragmentModbusSlaveBinding>() {

    override fun getLayoutId(): Int? = R.layout.fragment_modbus_slave

    private var spi: SimpleProcessImage? = null
    private var listener: ModbusTCPListener? = null
    private val port: Int = 1025
    private val slaveId: Int = 1
    private val ipAddress by lazy { NetworkUtils.getIPAddress(true) }
    private var isInitModbusReq = false

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)

        binding.tvIPAddress.text = "IP：$ipAddress"
        binding.tvPort.text = "端口：$port"

        spi = SimpleProcessImage()
//        //线圈寄存器
//        for(i in 0..500){
//            spi?.addDigitalOut(SimpleDigitalOut(false))
//        }
//        //状态寄存器
//        for(i in 0..1000){
//            spi?.addDigitalIn(SimpleDigitalIn(false))
//        }
        //保持寄存器
        for(i in 0..10){
            spi?.addRegister(SimpleRegister(0))
        }
//        //输入寄存器
//        for(i in 0..1000){
//            spi?.addInputRegister(SimpleInputRegister(0))
//        }

        ModbusCoupler.getReference().processImage = spi
        ModbusCoupler.getReference().isMaster = false
        ModbusCoupler.getReference().unitID = slaveId//从站地址

        Thread(networkTask).start()

        onClick()

    }

    private val networkTask = Runnable {
        val localIp = InetAddress.getByName(NetworkUtils.getIPAddress(true))
        listener = ModbusTCPListener(3)
        listener?.setPort(port)
        listener?.setAddress(localIp)
        listener?.start()

        if (!isInitModbusReq){
            initModbusReq()
        }
    }

    private fun onClick() {
        binding.actionBarBack.clickNoRepeat {
            navigateBack()
        }
        binding.btnInit.clickNoRepeat {
            if (isInitModbusReq){
                toast("已经初始化")
            } else {
                ModbusReq.getInstance().destory()
                initModbusReq()
            }
        }
        binding.btnWriteMultipleValue.clickNoRepeat {
            ModbusReq.getInstance().writeRegisters(object : OnRequestBack<String> {
                override fun onSuccess(s: String) {
                    toast("success")
                }

                override fun onFailed(msg: String) {
                    toast("onFailed:$msg")
                }
            }, slaveId, 0, shortArrayOf(100, 1, 3))
        }
    }

    private fun initModbusReq(){
        ModbusReq.getInstance()
            .setParam(
                ModbusParam()
                    .setHost(ipAddress) //192.168.3.190
                    .setPort(port)
                    .setEncapsulated(false)
                    .setKeepAlive(true)
                    .setTimeout(2000)
                    .setRetries(0)
            )
            .init(object : OnRequestBack<String> {
                override fun onSuccess(p0: String?) {
                    isInitModbusReq = true
                    binding.btnInit.text = "已初始化"
                }

                override fun onFailed(p0: String?) {
                    isInitModbusReq = false
                    binding.btnInit.text = "重新初始化"
                    toast("初始化失败: $p0")
                }
            })
    }

    override fun onDestroy() {
        ModbusReq.getInstance().destory()
        super.onDestroy()
    }

}